import configparser
from datetime import datetime
import logging
import os
import shutil
from pathlib import Path
import pandas as pd
from openpyxl.styles import Alignment, Font, PatternFill
from openpyxl.utils import get_column_letter
from openpyxl.styles import Font, PatternFill, Alignment

from constants.constant import EXCEL_PATH, ERR_APP_EXCEL_PATH, TARGET_SHEET, TYPE_DISC
from model.AppInfo import AppInfo


def save_config_to_properties(appInfo, userConfig):
    try:
        with(open(userConfig["download_path"] + "\\" + str(appInfo.order_id) + "-" + appInfo.app_name + "\\json文件\\AGC配置" + "\\config.properties", 'w', encoding="utf-8")) as f:
            for key, value in appInfo.__dict__.items():
                if not ["device_name", "certificate_debug_name", "certificate_release_name", "fingerprint1",
                        "fingerprint2", "order_id", "subject_name"].__contains__(key):
                    if key == "orientation":
                        value = "landscape" if value == "横屏" else "portrait"
                    f.write(f"{key}={value}\n")
    except Exception:
        raise


def processExcel(excelPath):
    try:
        appInfos = list()

        deviceCertificateInfos = list()
        df = pd.read_excel(excelPath, sheet_name="主体信息")
        for index, _ in df.iterrows():
            deviceCertificateInfo = df.iloc[index].to_dict()
            deviceCertificateInfos.append(deviceCertificateInfo)

        df = pd.read_excel(excelPath, sheet_name="应用信息")
        for index, _ in df.iterrows():
            appInfoDict = df.iloc[index].to_dict()
            appInfo = AppInfo()
            appInfo.order_id = appInfoDict["编号"]
            appInfo.app_name = appInfoDict["游戏名称"]
            appInfo.version_name = appInfoDict["version_name"]
            appInfo.version_code = appInfoDict["version_code"]
            appInfo.package_name = appInfoDict["包名"]
            appInfo.app_id = appInfoDict["appid"]
            appInfo.subject_name = appInfoDict["游戏主体"]
            appInfo.orientation = appInfoDict["横竖屏"]
            appInfo.ad_id_banner = appInfoDict["横幅展示位id"]
            appInfo.ad_id_reward = appInfoDict["激励视频展示位id"]
            appInfo.ad_id_interstitial = appInfoDict["插屏展示位id"]
            appInfo.ad_id_splash_1 = appInfoDict["开屏展示位id"]

            deviceCertificateInfo = next(
                (item for item in deviceCertificateInfos if item.get("pub_company") == appInfoDict["游戏主体"]), None)
            appInfo.certificate_debug_name = deviceCertificateInfo["调试证书名称"]
            appInfo.certificate_release_name = deviceCertificateInfo["发布证书名称"]
            appInfo.device_name = deviceCertificateInfo["设备名称"]
            appInfo.fingerprint1 = deviceCertificateInfo["证书指纹1"]
            appInfo.fingerprint2 = deviceCertificateInfo["证书指纹2"]
            appInfos.append(appInfo)
        return appInfos
    except Exception:
        raise


def read_properties(filePath):
    config = configparser.ConfigParser()
    config.optionxform = str
    with open(filePath, 'r', encoding="utf-8") as f:
        config.read_string('[dummy]\n' + f.read())

    return dict(config["dummy"])


def read_file_as_octet_stream(appInfo):
    fileInfoList = {}
    screenshotList = {}
    iconDict = {}
    publicationDict = {}
    screenshotContent = []
    screenshotSize = []
    screenshotName = []

    SCREENSHOT_PATH = os.getcwd() + "\\产品库\\" + str(int(appInfo.order_id)) + "-" + appInfo.app_name + "\\上架素材\\宣传图"
    ICON_PATH = os.getcwd() + "\\产品库\\" + str(int(appInfo.order_id)) + "-" + appInfo.app_name + "\\上架素材\\ICON"
    PUBLICATION_PATH = os.getcwd() + "\\产品库\\" + str(int(appInfo.order_id)) + "-" + appInfo.app_name + "\\软著+授权"

    # 读取截图信息
    for screenshot in Path(SCREENSHOT_PATH).iterdir():
        with open(SCREENSHOT_PATH + "\\" + screenshot.name, "rb") as f:
            file_bytes = f.read()

        file_size = len(file_bytes)
        screenshotContent.append(file_bytes)
        screenshotSize.append(file_size)
        screenshotName.append(screenshot.name)
    screenshotList["screenshotContent"] = screenshotContent
    screenshotList["screenshotSize"] = screenshotSize
    screenshotList["screenshotName"] = screenshotName
    fileInfoList["screenshotList"] = screenshotList

    # 读取ICON
    for icon in Path(ICON_PATH).iterdir():
        with open(ICON_PATH + "\\" + icon.name, "rb") as f:
            file_bytes = f.read()

        file_size = len(file_bytes)
        iconDict["iconContent"] = file_bytes
        iconDict["iconSize"] = file_size
        iconDict["iconName"] = icon.name
    fileInfoList["iconDict"] = iconDict

    # 读取版号证明
    for publication in Path(PUBLICATION_PATH).iterdir():
        if publication.name.find("免责函") != -1:
            with open(PUBLICATION_PATH + "\\" + publication.name, "rb") as f:
                file_bytes = f.read()
            file_size = len(file_bytes)

            publicationDict["publicationContent"] = file_bytes
            publicationDict["publicationSize"] = file_size
            publicationDict["publicationName"] = publication.name
        fileInfoList["publicationDict"] = publicationDict

    return fileInfoList


def genErrExcel(errNameList):
    shutil.copy2(EXCEL_PATH, ERR_APP_EXCEL_PATH)

    # 1. 读取所有 sheet（保留原始结构）
    all_sheets = pd.read_excel(ERR_APP_EXCEL_PATH, sheet_name=None)  # sheet_name=None 读取所有 sheet

    # 2. 检查是否存在目标 sheet
    if TARGET_SHEET not in all_sheets:
        raise ValueError(f"Excel 文件中没有名为 '{TARGET_SHEET}' 的 sheet！")

    # 3. 获取目标 sheet 的数据并处理
    df_main = all_sheets[TARGET_SHEET]

    # 确保有 '游戏名称' 列
    if '游戏名称' not in df_main.columns:
        raise ValueError("目标 sheet 中没有 '游戏名称' 列！")

    # 筛选：只保留在 errNameList 中的游戏
    df_filtered = df_main[df_main['游戏名称'].isin(errNameList)].reset_index(drop=True)

    # 4. 更新 all_sheets 中的目标 sheet
    all_sheets[TARGET_SHEET] = df_filtered

    # 5. 写回所有 sheet（保持结构）
    with pd.ExcelWriter(ERR_APP_EXCEL_PATH, engine='openpyxl') as writer:
        for sheet_name, df in all_sheets.items():
            df.to_excel(writer, sheet_name=sheet_name, index=False)

    print(f"✅ 处理完成！已保存到: {ERR_APP_EXCEL_PATH}")
    print(f"  - 原始 '{TARGET_SHEET}' 行数: {len(df_main)}")
    print(f"  - 筛选后行数: {len(df_filtered)}")


def save_excel(adTypeDict, appInfo, userConfig):
    adNameList = []
    adIdList = []
    mediaNameList = []
    orderIdList = []
    testAdIdList = ['testw6vs28auh3', 'testb4znbuh3n2', 'testq6zq98hecj', ""]
    adTypeList = ['开屏', 'Banner', '插屏', '激励']
    index = 1
    for adType in TYPE_DISC.keys():
        adNameList.append(adTypeDict[adType]["adName"])
        adIdList.append(adTypeDict[adType]["adId"])
        mediaNameList.append(f"{appInfo.app_name}/{appInfo.package_name}"),
        orderIdList.append(index)
        index += 1
    data = {
        '详情/广告位序号': orderIdList,
        '所属媒体名称/HAP包名*': mediaNameList,
        '媒体日活': ["", "", "", ""],
        '广告位名称*': adNameList,
        '广告位ID*': adIdList,
        '测试广告位ID': testAdIdList,
        '广告形式': adTypeList,
        '广告位截图': ["", "", "", ""],
        '广告触发逻辑': ["", "", "", ""]
    }

    # 转换为 DataFrame
    df = pd.DataFrame(data)

    # 保存为 Excel 文件
    with pd.ExcelWriter(userConfig["download_path"] + "\\" + str(appInfo.order_id)+ "-" + appInfo.app_name + "\\json文件\\AGC配置" + '\\广告位信息.xlsx',
                        engine='openpyxl') as writer:
        df.to_excel(writer, sheet_name='Sheet1', index=False)

        # 获取worksheet 对象
        worksheet = writer.sheets['Sheet1']

        worksheet.merge_cells('B2:B5')
        worksheet.merge_cells('C2:C5')

        # 设置包含换行的列（例如：'媒体日活' 列）
        col_index = df.columns.get_loc('媒体日活') + 1  # pandas 列索引从 0，Excel 从 1
        col_letter = get_column_letter(col_index)

        # 遍历该列所有单元格（从第2行开始，第1行是标题）
        for row in range(2, len(df) + 2):
            cell = worksheet[f"{col_letter}{row}"]
            cell.alignment = Alignment(wrap_text=True)  # 关键：启用自动换行

        worksheet.row_dimensions[1].height = 20  # 第1行

        for row in worksheet.iter_rows(min_row=1, max_row=worksheet.max_row, max_col=worksheet.max_column):
            for cell in row:
                cell.alignment = Alignment(horizontal='center', vertical='center')

        for col in range(1, worksheet.max_column + 1):
            column_letter = worksheet.cell(row=1, column=col).column_letter
            worksheet.column_dimensions[column_letter].width = 45

    logging.info(appInfo.app_name + f":广告excel表格保存完成，请在ohos/{str(appInfo.order_id)})文件夹中查看")


def save_review_excel(appInfoList, userConfig):
    filePath = os.getcwd() + "\\用于提审\\" + datetime.now().strftime('%Y-%m-%d-%H-%M') + '提审信息.xlsx'
    orderIdList = []
    appNameList = []
    packageNameList = []
    appIdList = []
    subjectList = []
    for appInfo in appInfoList:
        orderIdList.append(str(appInfo.order_id))
        appNameList.append(appInfo.app_name)
        packageNameList.append(appInfo.package_name)
        appIdList.append(str(appInfo.app_id))

    data = {
        '编号': orderIdList,
        '游戏名称': appNameList,
        '游戏包名': packageNameList,
        'appid': appIdList,
        '公司主体': subjectList,
    }

    # 转换为 DataFrame
    df = pd.DataFrame(data)

    with pd.ExcelWriter(filePath, engine='openpyxl') as writer:
        df.to_excel(writer, sheet_name='Sheet1', index=False)

        worksheet = writer.sheets['Sheet1']

        worksheet.row_dimensions[1].height = 20  # 第1行

        for row in worksheet.iter_rows(min_row=1, max_row=worksheet.max_row, max_col=worksheet.max_column):
            for cell in row:
                cell.alignment = Alignment(horizontal='center', vertical='center')

        for col in range(1, worksheet.max_column + 1):
            column_letter = worksheet.cell(row=1, column=col).column_letter
            worksheet.column_dimensions[column_letter].width = 45


def deleteOldDir(appInfo,userConfig):
    oldDirPath = userConfig["download_path"] + "\\" + str(appInfo.order_id) + "-" + appInfo.app_name + "\\json文件\\AGC配置"
    if os.path.exists(oldDirPath):
        for dir in os.listdir(oldDirPath):
            if dir == "广告位信息.xlsx":
                return False

        logging.info(appInfo.app_name + ":已删除旧文件夹")
        shutil.rmtree(oldDirPath)
        return True
    return True